import { useCallback, useEffect, useState } from 'react'
import { Form, Input, Radio, Button, MessagePlugin, Upload, UploadProps, Row, Col } from 'tdesign-react'
import { useTranslation } from 'react-i18next'
import { ApiRequest, apis } from '@/service'
import SelectInput from '../components/SelectInput'

type RequestMethodReturn = any

const {
  organization: {
    insertUser,
  },
  system: {
    getDictionaryArray,
  }
} = apis.BMService

const {
  uploadImages
} = apis.CommonService

const { FormItem, useForm } = Form
const CreateUser = () => {
  const { t } = useTranslation(["bugManager"])
  const [formRef] = useForm()
  const [uploadedImageLink, setUploadImageLink] = useState<string>('')
  const [uploadStatus, setUploadStatus] = useState({
    status: '',
    response: {},
  })
  const [POSITION, setPOSITION] = useState<DictionaryListType>([])

  useEffect(() => {
    queryDictionaryArrayFnc()
  }, [])

  const queryDictionaryArrayFnc = () => {
    const params = {
      dictionaryValue: 'Position',
      paging:  false
    }
    ApiRequest({ api: getDictionaryArray, params }).then((res: ResponseDataType) => {
      setPOSITION(res.data)
    })
  }

  const onSubmit = (context: any) => {
    console.log('context', context)
    if (context.validateResult === true) {
      let params = {
        ...context.fields,
        avatar: uploadedImageLink,
      }
      ApiRequest({ api: insertUser, params: params }).then((res: ResponseDataType) => {
        const { code = -1, data = [], note = '' } = res
        if (code > 0) {
          MessagePlugin.success({
            content: note || '提交成功',
            placement: 'top-right',
            duration: 2000
          })
        } else {
          MessagePlugin.error({
            content: note || '提交失败',
            placement: 'top-right',
            duration: 2000
          })
        }
      })
    } else {
      MessagePlugin.error({
        content: context.firstError,
        placement: 'top-right',
        duration: 2000
      })
    }
  }

  const onImageUploadSuccess: UploadProps['onSuccess'] = ({ currentFiles }: any) => {
    console.log('currentFiles', currentFiles)
  }

  const onFilesChange = async (files: any, context: any) => {
    if (files.length === 0) {
      return
    }
    let fileRaw = files[0].raw
    console.log('value', fileRaw, context)
    const params = {
      file: fileRaw,
    }
    ApiRequest({
      api: uploadImages,
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer 716|dkco9DcU6TBH9BOvlofFx909D5dNt8GVsJpeviss',
        'Content-Type': 'multipart/form-data',
      },
      params,
    }).then((res: any) => {
      const { status = 'fail', data = [], note = '' } = res
      if (status > 0) {
        MessagePlugin.success(note || '提交临时文件成功', 2000)
        setUploadImageLink(data.links.url)
        console.log('data', data.links.url)
        setUploadStatus({
          status: 'success',
          response: {
            url: data.links.url
          },
        })
      } else {
        MessagePlugin.error(note || '提交临时文件失败', 2000)
        setUploadStatus({
          status: 'fail',
          response: {
            message: res.message
          },
        })
      }
    }).catch((err: any) => {
      MessagePlugin.error(err, 2000)
    })
  }

  const requestMethod: UploadProps['requestMethod'] = useCallback(
    () =>
      new Promise<RequestMethodReturn>((resolve) => {
        console.log('uploadStatus', uploadStatus)
        resolve(uploadStatus)
      }),
    [],
  )


  return <div className={'content-wrapper'}>
    <Form form={formRef} onSubmit={onSubmit} colon labelWidth={100} resetType='initial'>
      <FormItem label={t("organization.name")} name="name">
        <Input style={{ width: 500 }} />
      </FormItem>
      <FormItem label={t("organization.gender")} name="gender">
        <Radio.Group>
          <Radio value="1">{t("organization.male")}</Radio>
          <Radio value="0">{t("organization.female")}</Radio>
        </Radio.Group>
      </FormItem>
      <FormItem label={t("organization.position")} name="position">
        <SelectInput options={POSITION} />
      </FormItem>
      <FormItem label={t("organization.slogan")} name="slogan">
        <Input style={{ width: 500 }} />
      </FormItem>
      <FormItem label={t("organization.avatar")} name="avatar">
        <Upload
          onChange={(value: any[], context: any) => { onFilesChange(value, context) }}
          theme="image"
          tips="请选择单张图片文件上传"
          accept="image/*"
          locale={{
            triggerUploadText: {
              image: '请选择图片',
            },
          }}
          autoUpload={false}
          requestMethod={requestMethod}
          onSuccess={onImageUploadSuccess}
        />
      </FormItem>
      <Row gutter={16}>
        <Col span={6} style={{ textAlign: 'right' }}>
          <Button type="submit" theme="primary">
            提交
          </Button>
        </Col>
        <Col span={6} style={{ textAlign: 'left' }}>
          <Button type="reset" theme="default">
            重置
          </Button>
        </Col>
      </Row>
    </Form>
  </div>
}
export default CreateUser